<template>
  <div class="picking zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
        <div>
          <p class="label">{{ $t('保养项目') }}</p>
          <div class="ipt">
            <Input type="text" v-model="searchParams.itemProject" :placeholder="`${$t('common.inputInfo')}`"
              class="inputBorder" :maxlength="32"></Input>
          </div>
        </div>
        </Col>
        <!-- <Col span="4">
        <div>
          <p class="label">工装编号</p>
          <div class="ipt">
            <Input type="text" v-model="searchParams.mmoldCode" :placeholder="`${$t('common.inputInfo')}`"
              class="inputBorder" :maxlength="32"></Input>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label">工装名称</p>
          <div class="ipt">
            <Input type="text" v-model="searchParams.mmoldName" :placeholder="`${$t('common.inputInfo')}`"
              class="inputBorder" :maxlength="32"></Input>
          </div>
        </div>
        </Col> -->
        <Col span="4">
        <div>
          <p class="label">{{ $t('是否上传sop') }}</p>
          <div class="ipt">
            <Select v-model="searchParams.isUploadSop" clearable :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="item of sopTagList" :value="item.name" :key="item.key" :label="item.name">
              </Option>
            </Select>
          </div>
        </div>
        </Col>

        <Col span="4">
        <div>
          <p class="label hide-label">--</p>
          <div class="ipt">
            <Button class="search-btn" type="primary" @click="changeNum">{{ $t('common.Query') }}
            </Button>
            <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}
            </Button>
          </div>
        </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="createfaultCodeShowH">{{
          $t('maintenance.New')
        }}
        </Button>
        <!-- <Button @click="handleDelete" >{{
            $t('maintenance.Delete')
          }}
        </Button> -->
        <Button @click="handleOutRecords">{{ $t('maintenance.Export') }}</Button>
        <Button @click="batchImport">{{ $t('maintenance.Import') }}</Button>
        <Button @click="exportTemplate">{{ $t('maintenance.Download') }}</Button>
        <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ?
          $t('显示操作栏') : $t('隐藏操作栏') }}</Button>
      </div>
      <div class="tableContent">
        <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList"
          ellipsis ref="selection" stripe :data="dataArr" @on-selection-change="onSelectChange">
          <template slot-scope="{ row,index }" slot="action">
            <!-- <span class="operationBtn" v-if="status == 0 && checkBtnPermission.dcmMaintainItemVerifyById" @click="confirm(row)">{{$t('maintenance.Confirmed')}}</span>-->
            <span class="operationBtn" @click="edit(row,index)"><i class="iconfont zy-common-bianji"></i>{{
              $t('maintenance.Edit') }}</span>
            <span class="operationBtn" @click="deleteRow(row)"><i class="iconfont zy-common-shanchu"></i>{{
              $t('maintenance.DeleteObj') }}</span>
          </template>
        </Table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="delIds.length" />
        <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
          @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
      </div>
    </div>
    <addModal ref="addProjectModal" @handleSearch="searchList"></addModal>
    <Modal :mask-closable="false" v-model="delFaultCodeShowF" class="modal-title-layout" :title="`${$t('maintenance.Deleteremind')}`">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.deletionaffect') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="delLoading" @click="deleteOk">{{
          $t('maintenance.Confirmed')
        }}
        </Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="delBatchFaultCodeShowF" :title="`${$t('maintenance.Deleteremind')}`">
      <Row class="enableContent">
        <Col span="24" class="enableContentInner">
        <img width="95px" src="~images/event/del.png" alt="" />
        </Col>
        <Col span="24" class="enableTips">
        <span>{{ $t('common.deletionaffect') }}</span>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="delBatchFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="delBatchLoading" @click="deleteBatchOk">{{
          $t('common.Save')
        }}
        </Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="confirmFaultCodeShowF" :title="`${$t('fault.Confirmremind')}`">
      <Row class="enableContent">
        <Col span="24" class="enableContentInner">
        <img width="95px" src="~images/event/pair.png" alt="" />
        </Col>
        <Col span="24" class="enableTips">
        <span>{{ $t('common.confirmationAfter') }}</span>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="confirmFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="confirmLoading" @click="deleteConfirmOk">{{
          $t('common.Save')
        }}
        </Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="confirmBatchFaultCodeShowF" :title="`${$t('fault.Confirmremind')}`">
      <Row class="enableContent">
        <Col span="24" class="enableContentInner">
        <img width="95px" src="~images/event/pair.png" alt="" />
        </Col>
        <Col span="24" class="enableTips">
        <span>{{ $t('common.confirmationAfter') }}</span>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="confirmBatchFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="confirmBatchLoading" @click="deleteBatchConfirmOk">{{ $t('common.Save') }}
        </Button>
      </div>
    </Modal>

    <!--    <Modal :mask-closable="false"-->
    <!--      v-model="importVisible"-->
    <!--      width="500"-->
    <!--      :title="`${$t('common.Import')}`"-->
    <!--      class="batchImport"-->
    <!--      @on-ok="importOk"-->
    <!--      @on-cancel="importCancel"-->
    <!--    >-->
    <!--      <div class="import">-->
    <!--        <span class="selectFile">请选择文件</span>-->
    <!--        <Upload action="/dms/dcmMaintainItem/import">-->
    <!--          <Button icon="ios-cloud-upload-outline">选择文件上传</Button>-->
    <!--        </Upload>-->
    <!--      </div>-->
    <!--&lt;!&ndash;      <div class="download">&ndash;&gt;-->
    <!--&lt;!&ndash;        <span class="clickthis">点击此处</span><span>下载模板。</span>&ndash;&gt;-->
    <!--&lt;!&ndash;      </div>&ndash;&gt;-->
    <!--    </Modal>-->
    <importExcelModal :importExcelStateF="importExcelState" v-if="importExcelState"
      @importExcelChange="importExcelChange" />
  </div>
</template>

<script>
import waitConfirmed from "./modal/waitConfirmed";
import importExcelModal from "@/components/importExcel.vue";
import confirmed from "./modal/confirmed";
import addModal from './modal/addModal'
import fileDownload from "js-file-download";
import recursion from "@/util/recursion";
import toggleTableOperation from "@/mixins/toggleTableOperation";

export default {
  name: "project",
  mixins: [toggleTableOperation],
  components: {
    waitConfirmed,
    confirmed,
    importExcelModal,
    addModal
  },
  data() {
    return {
      importExcelState: false,
      deviceMIdList: [],
      deviceNameList: [],
      sopTagList: [
        { name: "是", key: 0 },
        { name: "否", key: 1 },
      ],
      levelList: [
        { name: "一级保养", key: 1 },
        { name: "二级保养", key: 2 },
        { name: "三级保养", key: 3 },
      ],
      orgList: [],
      orgCodeList: [],
      status: 0,
      confirmId: '',
      delId: '',
      searchParams: {},
      total: 0,
      pageSize: 10,
      pageNum: 1,
      pageSizeOption: [10, 20, 30, 40],
      importVisible: false,
      allCheck: false,
      create: false,
      confirmBatchFaultCodeShowF: false,
      confirmBatchLoading: false,
      confirmFaultCodeShowF: false,
      confirmLoading: false,
      delFaultCodeShowF: false, //是否显示删除弹窗
      delLoading: false,
      delBatchFaultCodeShowF: false,
      delBatchLoading: false,
      formItem: {},
      delIds: [],
      classification: [
        { name: "CNC", key: "CNC" },
        { name: "PLC", key: "PLC" },
        { name: "IPC", key: "IPC" },
      ],
      category: [
        { label: 'A', value: 'A' },
        { label: 'B', value: 'B' },
        { label: 'C', value: 'C' },
      ],
      period: [
        { name: "月度", key: "month" },
        { name: "季度", key: "quarter" },
        { name: "年度", key: "year" },
      ],
      cycle: [
        // { name: "全部", key: "" },
        { name: "日", key: "1" },
        { name: "周", key: "2" },
        { name: "月", key: "3" },
        { name: "季度", key: "4" },
        { name: "半年度", key: "5" },
        { name: "年度", key: "6" },
        { name: "班次", key: "7" },
        { name: "计时", key: "8" },
      ],
      columns: [
        {
          type: 'selection',
          align: 'center',
          width: 60
        },
        {
          title: '保养项目',
          key: "itemProject",
          minWidth: 100,
          align: "center",
          resizable: true, tooltip: true,
        },
        {
          title: '基准',
          key: "itemBase",
          minWidth: 180,
          align: "center",
          resizable: true, 
          tooltip: true,
        },
        {
          title: '方法',
          key: "itemMethod",
          align: 'center',
          minWidth: 100,
          resizable: true, tooltip: true,
        },
        {
          title: '标准工时（S）',
          key: "unitTime",
          align: 'center',
          minWidth: 160,
          resizable: true,
          tooltip: true,
        },
        {
          title: '需求人数',
          key: "personQty",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        // {
        //   title: '是否上传sop',
        //   key: "servicingSop",
        //   align: 'center',
        //   minWidth: 200,
        //   resizable: true,
        //   tooltip: true,
        // },
        {
          title: `${this.$t('是否上传sop')}`,
          key: "isUploadSop",
          align: 'center',
          minWidth: 200,
          resizable: true,
          tooltip: true,
          // render: (h, params) => {
          //   if (Number(params.row.sopTag) >= 0) {
          //     return h('div', [
          //       h('span', this.sopTagList.find(val => val.key == params.row.sopTag).name)
          //     ]);
          //   } else {
          //     return h('div', [
          //       h('span', '')
          //     ]);
          //   }
          // }
        },
        // {
        //   title: '工装编号',
        //   key: "mmoldCode",
        //   minWidth: 160,
        //   align: "center",
        //   resizable: true,
        //   tooltip: true,
        // },
        // {
        //   title: '工装等级',
        //   key: "moldGrade",
        //   minWidth: 160,
        //   align: "center",
        //   resizable: true,
        //   tooltip: true,
        // },
        // {
        //   title: '工装名称',
        //   key: "mmoldName",
        //   align: 'center',
        //   minWidth: 160,
        //   resizable: true,
        //   tooltip: true,
        // },
        {
          title: `${this.$t('创建时间')}`,
          key: "createTime",
          minWidth: 200,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          fixed: 'right',
          minWidth: 240,
          align: "center"
        },
      ],

      deviceTypeList: [],
      dataArr: [],
    };
  },
  created() {
    this.getTableColumnsWidth(this.columns)
    this.searchList()
    // this.getFaultCategory("设备类型")
    // this.getDeviceList()
  },
  mounted() {
    // this.getOrgList()
  },
  methods: {
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    debounceSerach(fn, delay) {
      let _this = this
      return function f(...args) {
        if (_this.timeID) {
          clearTimeout(_this.timeID);
        }
        _this.timeID = setTimeout(() => {
          fn(args);
        }, delay);
      };
    },
    handleRemote(query) {
      if (!query) {
        return
      }
      const fn = this.debounceSerach(() => {
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: _query,
            deviceNo: '',
            assetsNo: "",
            orgCode: this.searchParams.orgCode || '',
          },
        }).then((res) => {
          if (res.code === 200) {
            this.deviceMIdList = res.data.map(item => {
              item.desc = item.deviceMId + '-' + item.deviceName + '-' + item.deviceNo
              return item;
            })
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        })
      }, 300)
      fn()
    },
    handleCasChange(val) {
      this.searchParams.orgCode = val[val.length - 1];
    },
    //获取故障数据
    getFaultCategory(name) {
      this.axios({
        method: 'get',
        url: '/dms/faultCategory/basicDict',
        params: { name }
      }).then(res => {
        if (res.code === 200) {

          if (name === '故障分类') {
            this.faultCategoryList = res.data.map(item => {
              if (item.value) return item;
            })
          } else if (name === '设备类型') {
            this.deviceTypeList = res.data.map(item => {
              if (item.value) return item;
            })
          }
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
        }
      })
    },
    deviceNameChange(val) {
      if (val) {
        this.searchParams.deviceType = val
      }
    },
    handleOutRecords() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ids: this.delIds,
        ...this.searchParams
      }
      const filName = '保养项目'
      this.axios({
        method: 'post',
        url: '/dms/servicingItem/export',
        responseType: 'blob',
        data: params
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === 'success') {
        this.changeNum();
        this.$Message.success('导入成功!')
      }
    },
    //下载模板
    exportTemplate() {
      const filName = "保养项目下载模板";
      this.axios({
        method: "get",
        url: "/dms/servicingItem/downloadTemplate",
        responseType: "blob",
      }).then((res) => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    getDeviceNameList(deviceName) {
      if (deviceName) {
        this.axios({
          method: 'get',
          url: '/dms/dcmMaintainItem/selectDeviceNames',
          params: {
            deviceName
          }
        }).then(res => {
          if (res.code == 200) {
            this.deviceNameList = res.data.map(val => ({
              label: val,
              value: val
            }))
          }
        })
      }
    },
    // getDeviceList() {
    //   this.axios({
    //     method: 'get',
    //     url: '/dms/dmsCategory/getSelectList',
    //     params: {}
    //   }).then(res => {
    //     if(res.code === 200){
    //       this.category = res.data
    //     }else{
    //       this.$Message.warning(({content:res.msg,duration:6,closable:true}));
    //     }
    //   })
    // },
    tabsClick(name) {
      console.log(name);
      this.status = name
      this.delIds = ''
      this.pageNum = 1
      this.searchList()
      // if (name === 0) {
      //     this.$refs.productConfigComponent.searchBtn();
      // } else  if (name === 1){
      //     console.log(this.$$refs);
      //     this.$refs.boxConfigComponent.searchBtn();
      // }else{
      //     this.$refs.shfitconfigComponent.searchBtn();
      // }
    },
    createfaultCodeShowH() {
      this.$refs.addProjectModal.show('')
    },
    //确认
    confirm(row) {
      this.confirmId = row.id
      this.confirmFaultCodeShowF = true
    },
    deleteConfirmOk() {
      this.confirmLoading = true
      this.axios({
        method: 'post',
        url: '/dms/dcmMaintainItem/verifyById',
        data: {
          id: this.confirmId
        }
      }).then(res => {

        if (res.code === 200) {
          this.searchList()
          this.$Message.success(({ content: '确认成功！', duration: 2, closable: true }));
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      }).finally(() => {
        this.confirmLoading = false
        this.confirmFaultCodeShowF = false
      })
    },
    //批量确认
    handleBatchConfirm() {
      this.confirmBatchFaultCodeShowF = true
    },
    deleteBatchConfirmOk() {
      this.confirmBatchLoading = true
      this.axios({
        method: 'post',
        url: '/dms/dcmMaintainItem/batchVerify',
        data: {
          ids: this.delIds
        }
      }).then(res => {

        if (res.code === 200) {
          this.searchList()
          this.$Message.success(({ content: '批量确认成功！', duration: 2, closable: true }));
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      }).finally(() => {
        this.confirmBatchLoading = false
        this.confirmBatchFaultCodeShowF = false
      })
    },
    edit(row) {
      this.$refs.addProjectModal.show(row)
    },
    handleDelete() {
      if (!(this.delIds && this.delIds.length)) {
        this.$Message.warning(({ content: `${this.$t('common.deleteItems')}`, duration: 2, closable: true }));
        return
      }
      this.delFaultCodeShowF = true
    },
    //删除
    deleteRow(row) {
      this.delId = row.id
      this.delFaultCodeShowF = true
    },
    deleteOk() {
      this.delLoading = true
      const obj = {
        method: 'PUT',
        url: '/dms/servicingItem/delete',
        data:this.delId ? [this.delId]:this.delIds,
      }
      this.axios(obj).then(res => {
        if (res.code === 200) {
          this.searchList()
          this.$Message.success(({ content: '删除成功！', duration: 2, closable: true }));
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      }).finally(() => {
        this.delLoading = false
        this.delFaultCodeShowF = false
      })
    },
    //批量删除
    handleBatchDelete() {
      if (!(this.delIds && this.delIds.length)) {
        this.$Message.error(`${this.$t('common.deleteItems')}`);
        return
      }
      this.delBatchFaultCodeShowF = true
    },
    deleteBatchOk() {
      this.delBatchLoading = true
      this.axios({
        method: 'delete',
        url: '/dms/dcmMaintainItem/batchDelete',
        params: {
          ids: this.delIds.toString()
        }
      }).then(res => {

        if (res.code === 200) {
          this.searchList()
          this.$Message.success(({ content: '批量删除成功！', duration: 2, closable: true }));
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      }).finally(() => {
        this.delBatchLoading = false
        this.delBatchFaultCodeShowF = false
      })
    },
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item) => {
        myArray.push(item.id);
      });

      this.delIds = myArray;
      if (selection.length > 1) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    handleSearch() {
      // this.status = status
      this.searchList()
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      let params = {
        // status: this.status,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      };
      // for (let key in this.searchParams) {
      //   if (key === 'orgId' && this.searchParams['orgId']) {
      //     const arr = this.searchParams[key]
      //     const {length, last = length - 1} = arr
      //     this.$set(params, key, arr[last])
      //   } else {
      //     if (this.searchParams[key]) {
      //       this.$set(params, key, this.searchParams[key])
      //     }
      //   }
      // }
      this.axios({
        method: 'post',
        url: '/dms/servicingItem/getPage',
        data: params
      }).then(res => {
        if (res.code === 200) {
          // if (res.data.records.length) {
          //   res.data.records.forEach(val => {
          //     if (val.categoryName) {
          //       val.categoryName = val.categoryName
          //     }
          //   })
          // }
          this.dataArr = res.data.records
          this.total = res.data.total
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    batchImport() {
      this.importExcelState = true;
    },
  },
};
</script>

<style lang="scss">
.project {
  //background: #ffffff;
  height: calc(100vh - 150px);

  .title {
    display: flex;
    justify-content: space-between;
    font-size: 20px;
    padding: 10px;
    border-bottom: 1px solid #dddddd;

    .icon {
      display: flex;

      .creatBtnright {
        display: flex;
        align-items: center;
        font-size: 16px;

        i {
          font-size: 36px;
        }
      }
    }
  }

  .tab {
    height: calc(100% - 100px);

    .ivu-tabs-bar {
      padding-left: 30px;
    }

    .ivu-tabs-tab {
      font-size: 18px;
    }
  }
}

.batchImport {
  .import {
    display: flex;
    align-items: center;

    .selectFile {
      margin-right: 10px;
    }

    .selectFile::before {
      content: "*";
      color: red;
      padding-right: 5px;
    }
  }

  .download {
    .clickthis {
      color: #187bdb;
      text-decoration: underline;
      cursor: pointer;
    }
  }
}
</style>